package com.agger.harmonyosthemeseditor.userinterface;

import com.agger.harmonyosthemeseditor.ResourceTable;

import com.agger.harmonyosthemeseditor.intelligent.ColorManager;
import com.agger.harmonyosthemeseditor.intelligent.DatabaseManager;
import com.agger.harmonyosthemeseditor.intelligent.TextBoxManager;
import com.agger.harmonyosthemeseditor.intelligent.TextManager;
import ohos.agp.colors.HsvColor;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.multimodalinput.event.MmiPoint;

public class ColorDialog
{
    private Context mContext;
    private String mTitle,mClose;
    private int colorValue;
    private boolean mOutsideTouchClosable;
    private CommonDialog sDialog;
    private CommonDialog.DestroyedListener mDestroyedListener;
    private DisplayAttributes displayAttributes;
    private Component ColorCenter,ColorCursor,ColorPreviewer,ThumbShadow;
    public boolean isDestroyed = false;
    private boolean isCursorMoving = false;
    private int Cursor_x,Cursor_y,Cursor_l,Cursor_t,Cursor_r,Cursor_b;
    private float Touch_x,Touch_y;
    private float H,S,V;
    private int R,G,B;
    private Slider BrightnessController;
    private int DefaultColor = -1;

    public ColorDialog(Context context)
    {
        mContext = context;
    }

    public ColorDialog setTitle(String title)
    {
        mTitle = title;
        return this;
    }

    public ColorDialog setCloseText(String closeText)
    {
        mClose = closeText;
        return this;
    }

    public ColorDialog setDefaultColor(int _color)
    {
        DefaultColor = _color;
        return this;
    }

    public ColorDialog setDefaultColor(String _color)
    {
        try{DefaultColor=Color.getIntColor(_color);}catch(Exception e){e.printStackTrace();}
        return this;
    }

    public ColorDialog setOutsideTouchClosable(boolean closable)
    {
        mOutsideTouchClosable = closable;
        return this;
    }

    public void setDestroyedListener(CommonDialog.DestroyedListener destroyedListener)
    {
        mDestroyedListener = destroyedListener;
    }

    public void show()
    {
        isCursorMoving = false;
        H = 0;
        S = 0;
        V = 100;
        R = 255;
        G = 255;
        B = 255;
        float sDim = (ResourceTool.getColor(mContext,ResourceTable.Color_dawnlighti_color_mode,-1)==-16777216)?0.4f:0.2f;
        displayAttributes = DisplayManager.getInstance().getDefaultDisplay(mContext).get().getAttributes();
        sDialog = new CommonDialog(mContext);
        int DialogWidth;
        if((((float)displayAttributes.height)/((float)displayAttributes.width))>1.128f)
        {
            DialogWidth = displayAttributes.width - (int)((24f*displayAttributes.scalDensity)+0.5f);
            sDialog.setAlignment(LayoutAlignment.BOTTOM);
            sDialog.setOffset(0,(int)((16f*displayAttributes.scalDensity)+0.5f));
        }
        else
        {
            if((((float)displayAttributes.width)/((float)displayAttributes.height))<1.48f) DialogWidth = displayAttributes.width - (int)((111f*displayAttributes.scalDensity)+0.5f);
            else DialogWidth = (int)((displayAttributes.width*0.4775f)+0.5f);
            if(DialogWidth < (int)((320f*displayAttributes.scalDensity)+0.5f))
                DialogWidth = (int)((320f*displayAttributes.scalDensity)+0.5f);
            else if(DialogWidth > (int)((360f*displayAttributes.scalDensity)+0.5f))
                DialogWidth = (int)((360f*displayAttributes.scalDensity)+0.5f);
            sDialog.setAlignment(LayoutAlignment.CENTER);
            sDialog.setOffset(0,0);
        }
        sDialog.setTransparent(true);
        DatabaseManager.Init(mContext);
        Component dialogLayout = DatabaseManager.getInt("ColorDialog_RgbMode",0)==1?initDialogRgb():initDialog();
        sDialog.setContentCustomComponent(dialogLayout);
        sDialog.setSize(DialogWidth, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        sDialog.setAutoClosable(mOutsideTouchClosable);
        sDialog.setMovable(false);
        sDialog.setDestroyedListener(mDestroyedListener);
        sDialog.show();
        Window sWindow = sDialog.getWindow();
        WindowManager.LayoutConfig layoutConfig =sWindow.getLayoutConfig().get();
        layoutConfig.dim = sDim;
        sWindow.setLayoutConfig(layoutConfig);
        isDestroyed = false;
        System.gc();
    }

    private void switchShow(Component type)
    {
        sDialog.setDestroyedListener(null);
        sDialog.destroy();
        DefaultColor = colorValue;
        isCursorMoving = false;
        float sDim = (ResourceTool.getColor(mContext,ResourceTable.Color_dawnlighti_color_mode,-1)==-16777216)?0.4f:0.2f;
        displayAttributes = DisplayManager.getInstance().getDefaultDisplay(mContext).get().getAttributes();
        sDialog = new CommonDialog(mContext);
        int DialogWidth;
        if((((float)displayAttributes.height)/((float)displayAttributes.width))>1.128f)
        {
            DialogWidth = displayAttributes.width - (int)((24f*displayAttributes.scalDensity)+0.5f);
            sDialog.setAlignment(LayoutAlignment.BOTTOM);
            sDialog.setOffset(0,(int)((16f*displayAttributes.scalDensity)+0.5f));
        }
        else
        {
            if((((float)displayAttributes.width)/((float)displayAttributes.height))<1.48f) DialogWidth = displayAttributes.width - (int)((111f*displayAttributes.scalDensity)+0.5f);
            else DialogWidth = (int)((displayAttributes.width*0.4775f)+0.5f);
            if(DialogWidth < (int)((320f*displayAttributes.scalDensity)+0.5f))
                DialogWidth = (int)((320f*displayAttributes.scalDensity)+0.5f);
            else if(DialogWidth > (int)((360f*displayAttributes.scalDensity)+0.5f))
                DialogWidth = (int)((360f*displayAttributes.scalDensity)+0.5f);
            sDialog.setAlignment(LayoutAlignment.CENTER);
            sDialog.setOffset(0,0);
        }
        sDialog.setTransparent(true);
        Component dialogLayout = type;
        sDialog.setContentCustomComponent(dialogLayout);
        sDialog.setSize(DialogWidth, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        sDialog.setAutoClosable(mOutsideTouchClosable);
        sDialog.setMovable(false);
        sDialog.setDestroyedListener(mDestroyedListener);
        sDialog.show();
        Window sWindow = sDialog.getWindow();
        WindowManager.LayoutConfig layoutConfig =sWindow.getLayoutConfig().get();
        layoutConfig.dim = sDim;
        sWindow.setLayoutConfig(layoutConfig);
        isDestroyed = false;
        System.gc();
    }

    private Component initDialog()
    {
        Component dialogLayout = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_color_dialog, null, false);
        Component ColorDialogLayout = dialogLayout.findComponentById(ResourceTable.Id_ColorDialogLayout);
        ColorDialogLayout.setBackground(new ShapeElement(){{setRgbColor(RgbColor.fromArgbInt(ResourceTool.getColor(mContext,ResourceTable.Color_dawnlighti_radio_dialog_bg,-1)));setCornerRadius((int)((24f*displayAttributes.scalDensity)+0.5f));}});
        ((Text)dialogLayout.findComponentById(ResourceTable.Id_title)).setText(mTitle);
        ColorCenter = dialogLayout.findComponentById(ResourceTable.Id_color_board_cover);
        ThumbShadow = dialogLayout.findComponentById(ResourceTable.Id_color_thumb_shadow);
        ColorCursor = dialogLayout.findComponentById(ResourceTable.Id_color_thumb);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setShape(ShapeElement.OVAL);
        shapeElement.setRgbColor(new RgbColor(255,255,255));
        ColorCursor.setBackground(shapeElement);
        BrightnessController = (Slider) dialogLayout.findComponentById(ResourceTable.Id_slider_colorBrightness);
        BrightnessController.setMinValue(0);
        BrightnessController.setMaxValue(100);
        BrightnessController.setProgressValue(100);
        BrightnessController.setStep(1);
        BrightnessController.setThumbElement(new ShapeElement(){{setRgbColor(new RgbColor(255,255,255,127));setShape(ShapeElement.OVAL);}});
        ShapeElement mColorBarElement = new ShapeElement();
        mColorBarElement.setShape(ShapeElement.RECTANGLE);
        mColorBarElement.setShaderType(ShapeElement.LINEAR_GRADIENT_SHADER_TYPE);
        mColorBarElement.setGradientOrientation((displayAttributes.height>displayAttributes.width)?ShapeElement.Orientation.LEFT_TO_RIGHT:ShapeElement.Orientation.BOTTOM_TO_TOP);
        mColorBarElement.setCornerRadius((int)((12f*displayAttributes.scalDensity)+0.5f));
        mColorBarElement.setRgbColors(new RgbColor[]{new RgbColor(0,0,0),new RgbColor(255,0,0)});
        BrightnessController.setBackground(mColorBarElement);
        ColorPreviewer = dialogLayout.findComponentById(ResourceTable.Id_color_previewer);
        ShapeElement previewerElement = new ShapeElement();
        previewerElement.setShape(ShapeElement.OVAL);
        previewerElement.setRgbColor(new RgbColor(255,255,255));
        ColorPreviewer.setBackground(previewerElement);
        ColorCursor.setTouchEventListener((component, touchEvent) ->
        {
            if(touchEvent.getAction()==1)
            {
                if(!isCursorMoving)
                {
                    MmiPoint mmiPoint = touchEvent.getPointerScreenPosition(touchEvent.getIndex());
                    Cursor_x = ColorCursor.getComponentPosition().getCenterX();
                    Cursor_y = ColorCursor.getComponentPosition().getCenterY();
                    Cursor_l = ColorCursor.getComponentPosition().left;
                    Cursor_t = ColorCursor.getComponentPosition().top;
                    Cursor_r = ColorCursor.getComponentPosition().right;
                    Cursor_b = ColorCursor.getComponentPosition().bottom;
                    Touch_x = mmiPoint.getX();
                    Touch_y = mmiPoint.getY();
                    isCursorMoving = true;
                }
            }else if(touchEvent.getAction()==2)
            {
                if(isCursorMoving)
                {
                    MmiPoint mmiPoint = touchEvent.getPointerScreenPosition(touchEvent.getIndex());
                    int difference_x = (int)(mmiPoint.getX()-Touch_x);
                    int difference_y = (int)(mmiPoint.getY()-Touch_y);
                    int newX = Cursor_x+difference_x;
                    int newY = Cursor_y+difference_y;
                    //校正浮标位置
                    int fixer_x = 0;
                    int fixer_y = 0;
                    int center_x = ColorCenter.getComponentPosition().getCenterX();
                    int center_y = ColorCenter.getComponentPosition().getCenterY();
                    int max_t = center_y-ColorCenter.getComponentPosition().top;
                    int max_b = ColorCenter.getComponentPosition().bottom-center_y;
                    int min_x = ColorCenter.getComponentPosition().left;
                    int max_x = ColorCenter.getComponentPosition().right;
                    if(newX<center_x)
                    {
                        if(newX < min_x)
                        {
                            fixer_x = min_x-newX;
                        }else if(newX == min_x)
                        {
                            fixer_y = center_y-newY;
                        }else
                        {
                            if(newY<center_y)
                            {
                                int min_y = (int)(center_y-Math.sqrt(Math.pow(max_t,2)-Math.pow(center_x-newX,2)));
                                if(newY<min_y)
                                {
                                    fixer_y = min_y-newY;
                                }
                            }else if(newY>center_y)
                            {
                                int max_y = (int)(center_y+Math.sqrt(Math.pow(max_b,2)-Math.pow(center_x-newX,2)));
                                if(newY>max_y)
                                {
                                    fixer_y = max_y-newY;
                                }
                            }
                        }
                    }else if(newX==center_x)
                    {
                        if(newY<ColorCenter.getComponentPosition().top)
                        {
                            fixer_y = ColorCenter.getComponentPosition().top-newY;
                        }else if(newY>ColorCenter.getComponentPosition().bottom)
                        {
                            fixer_y = ColorCenter.getComponentPosition().bottom-newY;
                        }
                    }else
                    {
                        if(newX > max_x)
                        {
                            fixer_x = max_x-newX;
                        }else if(newX == max_x)
                        {
                            fixer_y = center_y-newY;
                        }else
                        {
                            if(newY<center_y)
                            {
                                int min_y = (int)(center_y-Math.sqrt(Math.pow(max_t,2)-Math.pow(newX-center_x,2)));
                                if(newY<min_y)
                                {
                                    fixer_y = min_y-newY;
                                }
                            }else if(newY>center_y)
                            {
                                int max_y = (int)(center_y+Math.sqrt(Math.pow(max_b,2)-Math.pow(newX-center_x,2)));
                                if(newY>max_y)
                                {
                                    fixer_y = max_y-newY;
                                }
                            }
                        }
                    }
                    difference_x += fixer_x;
                    difference_y += fixer_y;
                    ColorCursor.setComponentPosition(Cursor_l+difference_x,Cursor_t+difference_y,Cursor_r+difference_x,Cursor_b+difference_y);
                    ThumbShadow.setComponentPosition(ThumbShadow.getComponentPosition().left+difference_x,ThumbShadow.getComponentPosition().top+difference_y,ThumbShadow.getComponentPosition().right+difference_x,ThumbShadow.getComponentPosition().bottom+difference_y);
                    Cursor_x = ColorCursor.getComponentPosition().getCenterX();
                    Cursor_y = ColorCursor.getComponentPosition().getCenterY();
                    Cursor_l = ColorCursor.getComponentPosition().left;
                    Cursor_t = ColorCursor.getComponentPosition().top;
                    Cursor_r = ColorCursor.getComponentPosition().right;
                    Cursor_b = ColorCursor.getComponentPosition().bottom;
                    Touch_x = mmiPoint.getX();
                    Touch_y = mmiPoint.getY();
                    //计算当前区颜色
                    Cursor_x = ColorCursor.getComponentPosition().getCenterX();
                    Cursor_y = ColorCursor.getComponentPosition().getCenterY();
                    int virtual_x = Cursor_x - center_x;
                    int virtual_y = center_y - Cursor_y;
                    if(virtual_y>=0)
                    H = (float)(180d*Math.atan2(virtual_y,virtual_x)/Math.PI);
                    else
                    H = (float)(180d+180d*Math.atan2(-virtual_y,-virtual_x)/Math.PI);
                    if(H>=360f)H=0;
                    S = (float)(100d*Math.sqrt(Math.pow(Math.abs(virtual_x),2)+Math.pow(Math.abs(virtual_y),2))/(center_y-ColorCenter.getComponentPosition().top));
                    if(S>100f)S=100f;
                    ShapeElement thumbElement = new ShapeElement();
                    thumbElement.setShape(ShapeElement.OVAL);
                    thumbElement.setRgbColor(RgbColor.fromArgbInt(HsvColor.toColor(255,H,S,100f)));
                    ColorCursor.setBackground(thumbElement);
                    ShapeElement colorfulElement = new ShapeElement();
                    colorfulElement.setShape(ShapeElement.RECTANGLE);
                    colorfulElement.setShaderType(ShapeElement.LINEAR_GRADIENT_SHADER_TYPE);
                    colorfulElement.setGradientOrientation((displayAttributes.height>displayAttributes.width)?ShapeElement.Orientation.LEFT_TO_RIGHT:ShapeElement.Orientation.BOTTOM_TO_TOP);
                    colorfulElement.setCornerRadius(BrightnessController.getHeight()/2f);
                    colorfulElement.setRgbColors(new RgbColor[]{new RgbColor(0,0,0),RgbColor.fromArgbInt(HsvColor.toColor(255,H,S,100f))});
                    BrightnessController.setBackground(colorfulElement);
                    ShapeElement mColorElement = new ShapeElement();
                    mColorElement.setShape(ShapeElement.OVAL);
                    colorValue = HsvColor.toColor(255,H,S,V);
                    RgbColor rgbColor = RgbColor.fromArgbInt(colorValue);
                    R = rgbColor.getRed();
                    G = rgbColor.getGreen();
                    B = rgbColor.getBlue();
                    mColorElement.setRgbColor(rgbColor);
                    ColorPreviewer.setBackground(mColorElement);
                    isCursorMoving = false;
                }
            }
            else if(touchEvent.getAction()==3)
            {
                if(isCursorMoving)
                {
                    MmiPoint mmiPoint = touchEvent.getPointerScreenPosition(touchEvent.getIndex());
                    int difference_x = (int)(mmiPoint.getX()-Touch_x);
                    int difference_y = (int)(mmiPoint.getY()-Touch_y);
                    int newX = Cursor_x+difference_x;
                    int newY = Cursor_y+difference_y;
                    //校正浮标位置
                    int fixer_x = 0;
                    int fixer_y = 0;
                    int center_x = ColorCenter.getComponentPosition().getCenterX();
                    int center_y = ColorCenter.getComponentPosition().getCenterY();
                    int max_t = center_y-ColorCenter.getComponentPosition().top;
                    int max_b = ColorCenter.getComponentPosition().bottom-center_y;
                    int min_x = ColorCenter.getComponentPosition().left;
                    int max_x = ColorCenter.getComponentPosition().right;
                    if(newX<center_x)
                    {
                        if(newX < min_x)
                        {
                            fixer_x = min_x-newX;
                        }else if(newX == min_x)
                        {
                            fixer_y = center_y-newY;
                        }else
                        {
                            if(newY<center_y)
                            {
                                int min_y = (int)(center_y-Math.sqrt(Math.pow(max_t,2)-Math.pow(center_x-newX,2)));
                                if(newY<min_y)
                                {
                                    fixer_y = min_y-newY;
                                }
                            }else if(newY>center_y)
                            {
                                int max_y = (int)(center_y+Math.sqrt(Math.pow(max_b,2)-Math.pow(center_x-newX,2)));
                                if(newY>max_y)
                                {
                                    fixer_y = max_y-newY;
                                }
                            }
                        }
                    }else if(newX==center_x)
                    {
                        if(newY<ColorCenter.getComponentPosition().top)
                        {
                            fixer_y = ColorCenter.getComponentPosition().top-newY;
                        }else if(newY>ColorCenter.getComponentPosition().bottom)
                        {
                            fixer_y = ColorCenter.getComponentPosition().bottom-newY;
                        }
                    }else
                    {
                        if(newX > max_x)
                        {
                            fixer_x = max_x-newX;
                        }else if(newX == max_x)
                        {
                            fixer_y = center_y-newY;
                        }else
                        {
                            if(newY<center_y)
                            {
                                int min_y = (int)(center_y-Math.sqrt(Math.pow(max_t,2)-Math.pow(newX-center_x,2)));
                                if(newY<min_y)
                                {
                                    fixer_y = min_y-newY;
                                }
                            }else if(newY>center_y)
                            {
                                int max_y = (int)(center_y+Math.sqrt(Math.pow(max_b,2)-Math.pow(newX-center_x,2)));
                                if(newY>max_y)
                                {
                                    fixer_y = max_y-newY;
                                }
                            }
                        }
                    }
                    difference_x += fixer_x;
                    difference_y += fixer_y;
                    ColorCursor.setComponentPosition(Cursor_l+difference_x,Cursor_t+difference_y,Cursor_r+difference_x,Cursor_b+difference_y);
                    ThumbShadow.setComponentPosition(ThumbShadow.getComponentPosition().left+difference_x,ThumbShadow.getComponentPosition().top+difference_y,ThumbShadow.getComponentPosition().right+difference_x,ThumbShadow.getComponentPosition().bottom+difference_y);
                    Cursor_x = ColorCursor.getComponentPosition().getCenterX();
                    Cursor_y = ColorCursor.getComponentPosition().getCenterY();
                    Cursor_l = ColorCursor.getComponentPosition().left;
                    Cursor_t = ColorCursor.getComponentPosition().top;
                    Cursor_r = ColorCursor.getComponentPosition().right;
                    Cursor_b = ColorCursor.getComponentPosition().bottom;
                    Touch_x = mmiPoint.getX();
                    Touch_y = mmiPoint.getY();
                }
            }
            return true;
        });
        BrightnessController.setValueChangedListener(new Slider.ValueChangedListener()
        {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b)
            {
                V=i;
                colorValue = HsvColor.toColor(255,H,S,V);
                RgbColor rgbColor = RgbColor.fromArgbInt(colorValue);
                R = rgbColor.getRed();
                G = rgbColor.getGreen();
                B = rgbColor.getBlue();
                ShapeElement previewerElement = new ShapeElement();
                previewerElement.setShape(ShapeElement.OVAL);
                previewerElement.setRgbColor(rgbColor);
                ColorPreviewer.setBackground(previewerElement);
            }
            @Override
            public void onTouchStart(Slider slider) {}
            @Override
            public void onTouchEnd(Slider slider) {}
        });
        Component switchMode = dialogLayout.findComponentById(ResourceTable.Id_rgb);
        switchMode.setClickedListener(c->
        {
            DatabaseManager.Init(mContext);
            DatabaseManager.setInt("ColorDialog_RgbMode",1);
            colorValue = HsvColor.toColor(255,H,S,V);
            DefaultColor = colorValue;
            RgbColor rgbColor = RgbColor.fromArgbInt(colorValue);
            R = rgbColor.getRed();
            G = rgbColor.getGreen();
            B = rgbColor.getBlue();
            switchShow(initDialogRgb());
        });
        Button button = (Button) dialogLayout.findComponentById(ResourceTable.Id_CloseButton);
        button.setBackground(new GeneralButtonElement(mContext,GeneralButtonElement.TYPE_Empty_Button));
        button.setTextColor(new Color(ResourceTool.getColor(mContext, ResourceTable.Color_dawnlighti_button_accent, -417762)));
        button.setText(mClose);
        button.setClickedListener(component -> {DatabaseManager.Init(mContext); DatabaseManager.setInt("ColorDialog_RgbMode",0); if (sDialog != null) {sDialog.destroy(); isDestroyed = true; System.gc();} });
        dialogLayout.setLayoutRefreshedListener(c ->
        {
            if(DefaultColor!=-1)
            {
                colorValue = DefaultColor;
                ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(colorValue);
                H = hsvBox.getHue();
                S = hsvBox.getSaturation();
                V = hsvBox.getValue();
                RgbColor rgbColor = RgbColor.fromArgbInt(colorValue);
                R = rgbColor.getRed();
                G = rgbColor.getGreen();
                B = rgbColor.getBlue();
                ShapeElement colorfulElement = new ShapeElement();
                colorfulElement.setShape(ShapeElement.RECTANGLE);
                colorfulElement.setShaderType(ShapeElement.LINEAR_GRADIENT_SHADER_TYPE);
                colorfulElement.setGradientOrientation((displayAttributes.height>displayAttributes.width)?ShapeElement.Orientation.LEFT_TO_RIGHT:ShapeElement.Orientation.BOTTOM_TO_TOP);
                colorfulElement.setCornerRadius((int)((12f*displayAttributes.scalDensity)+0.5f));
                colorfulElement.setRgbColors(new RgbColor[]{new RgbColor(0,0,0),RgbColor.fromArgbInt(HsvColor.toColor(255,H,S,100f))});
                BrightnessController.setBackground(colorfulElement);
                BrightnessController.setProgressValue((int)V);
                ShapeElement _previewerElement = new ShapeElement();
                _previewerElement.setShape(ShapeElement.OVAL);
                _previewerElement.setRgbColor(rgbColor);
                ColorPreviewer.setBackground(_previewerElement);
                int fixer_x = 0;
                int fixer_y = 0;
                int center_x = ColorCenter.getComponentPosition().getCenterX();
                int center_y = ColorCenter.getComponentPosition().getCenterY();
                if(H==0f)
                {
                    fixer_x = (int)(S*(ColorCenter.getComponentPosition().right-center_x)/100f);
                }else if(H<90f)
                {
                    double angle = H*Math.PI/180d;
                    fixer_x = (int)(Math.cos(angle)*(S*(ColorCenter.getComponentPosition().right-center_x)/100f));
                    fixer_y = -((int)(Math.sin(angle)*(S*(center_y-ColorCenter.getComponentPosition().top)/100f)));
                }else if(H==90f)
                {
                    fixer_y = -((int)(S*(center_y-ColorCenter.getComponentPosition().top)/100f));
                }else if(H<180f)
                {
                    double angle = (180f-H)*Math.PI/180d;
                    fixer_y = -((int)(Math.sin(angle)*(S*(center_y-ColorCenter.getComponentPosition().top)/100f)));
                    fixer_x = -((int)(Math.cos(angle)*(S*(center_x-ColorCenter.getComponentPosition().left)/100f)));
                }else if(H==180f)
                {
                    fixer_x = -((int)(S*(center_x-ColorCenter.getComponentPosition().left)/100f));
                }else if(H<270f)
                {
                    double angle = (H-180f)*Math.PI/180d;
                    fixer_x = -((int)(Math.cos(angle)*(S*(center_x-ColorCenter.getComponentPosition().left)/100f)));
                    fixer_y = (int)(Math.sin(angle)*(S*(ColorCenter.getComponentPosition().bottom-center_y)/100f));
                }else if(H==270f)
                {
                    fixer_y = (int)(S*(ColorCenter.getComponentPosition().bottom-center_y)/100f);
                }else if(H<360f)
                {
                    double angle = (360f-H)*Math.PI/180d;
                    fixer_y = (int)(Math.sin(angle)*(S*(ColorCenter.getComponentPosition().bottom-center_y)/100f));
                    fixer_x = (int)(Math.cos(angle)*(S*(ColorCenter.getComponentPosition().right-center_x)/100f));
                }else
                {
                    fixer_x = (int)(S*(ColorCenter.getComponentPosition().right-center_x)/100f);
                }
                ColorCursor.setComponentPosition(ColorCursor.getComponentPosition().left+fixer_x,ColorCursor.getComponentPosition().top+fixer_y,ColorCursor.getComponentPosition().right+fixer_x,ColorCursor.getComponentPosition().bottom+fixer_y);
                ThumbShadow.setComponentPosition(ThumbShadow.getComponentPosition().left+fixer_x,ThumbShadow.getComponentPosition().top+fixer_y,ThumbShadow.getComponentPosition().right+fixer_x,ThumbShadow.getComponentPosition().bottom+fixer_y);
                ShapeElement thumbElement = new ShapeElement();
                thumbElement.setShape(ShapeElement.OVAL);
                thumbElement.setRgbColor(RgbColor.fromArgbInt(HsvColor.toColor(255,H,S,100f)));
                ColorCursor.setBackground(thumbElement);
            }
        });
        return dialogLayout;
    }

    private Component initDialogRgb()
    {
        Component dialogLayout = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_rgb_dialog, null, false);
        Component ColorDialogLayout = dialogLayout.findComponentById(ResourceTable.Id_ColorDialogLayout);
        ColorDialogLayout.setBackground(new ShapeElement(){{setRgbColor(RgbColor.fromArgbInt(ResourceTool.getColor(mContext,ResourceTable.Color_dawnlighti_radio_dialog_bg,-1)));setCornerRadius((int)((24f*displayAttributes.scalDensity)+0.5f));}});
        ((Text)dialogLayout.findComponentById(ResourceTable.Id_title)).setText(mTitle);

        ColorPreviewer = dialogLayout.findComponentById(ResourceTable.Id_rgb_preview);
        ShapeElement previewerElement = new ShapeElement();
        previewerElement.setShape(ShapeElement.OVAL);
        previewerElement.setRgbColor(new RgbColor(255,255,255));
        ColorPreviewer.setBackground(previewerElement);

        TextField Rgb_Value = (TextField)dialogLayout.findComponentById(ResourceTable.Id_text_RGB);
        TextField Rgb_R = (TextField)dialogLayout.findComponentById(ResourceTable.Id_text_R);
        TextField Rgb_G = (TextField)dialogLayout.findComponentById(ResourceTable.Id_text_G);
        TextField Rgb_B = (TextField)dialogLayout.findComponentById(ResourceTable.Id_text_B);
        Slider slider_R = (Slider)dialogLayout.findComponentById(ResourceTable.Id_slider_R);
        Slider slider_G = (Slider)dialogLayout.findComponentById(ResourceTable.Id_slider_G);
        Slider slider_B = (Slider)dialogLayout.findComponentById(ResourceTable.Id_slider_B);

        TextBoxManager.TextBoxForDialog(mContext,Rgb_Value);
        TextBoxManager.TextBoxForDialog(mContext,Rgb_R);
        TextBoxManager.TextBoxForDialog(mContext,Rgb_G);
        TextBoxManager.TextBoxForDialog(mContext,Rgb_B);

        Rgb_Value.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                String CodeText = "";
                char[] texts = ("#"+Rgb_Value.getText().replaceAll("\\#","").toUpperCase()).toCharArray();
                for(int o=0;o<texts.length;o++)
                {
                    if(TextManager.isColorChar(texts[o]))
                        CodeText += texts[o];
                }
                if(CodeText.length()>7)
                {
                    CodeText = CodeText.substring(0,7);
                }
                if(CodeText.length()==7)
                {
                    colorValue = Color.getIntColor(CodeText);
                    ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(colorValue);
                    H = hsvBox.getHue();
                    S = hsvBox.getSaturation();
                    V = hsvBox.getValue();

                    ShapeElement _previewerElement = new ShapeElement();
                    _previewerElement.setShape(ShapeElement.OVAL);
                    _previewerElement.setRgbColor(RgbColor.fromArgbInt(colorValue));
                    ColorPreviewer.setBackground(_previewerElement);

                    RgbColor rgbColor = RgbColor.fromArgbInt(colorValue);
                    R = rgbColor.getRed();
                    G = rgbColor.getGreen();
                    B = rgbColor.getBlue();
                    slider_R.setProgressValue(R);
                    slider_G.setProgressValue(G);
                    slider_B.setProgressValue(B);
                    Rgb_R.setText(String.valueOf(R));
                    Rgb_G.setText(String.valueOf(G));
                    Rgb_B.setText(String.valueOf(B));
                }
                Rgb_Value.setText(CodeText);
            }
            catch (Exception e){}
        });

        Rgb_R.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                String CodeText = "";
                char[] texts = Rgb_R.getText().toCharArray();
                for(int o=0;o<texts.length;o++)
                {
                    if(TextManager.isNumCharPro(texts[o]))
                        CodeText += texts[o];
                }
                if(CodeText.length()>3)
                {
                    CodeText = CodeText.substring(0,3);
                }
                int val = Integer.valueOf(CodeText);
                if(Integer.valueOf(CodeText)>255) CodeText = "255";
                R=val;
                slider_R.setProgressValue(R);
                RgbColor rgbColor = new RgbColor(R,G,B);
                colorValue = rgbColor.asArgbInt();
                ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(colorValue);
                H = hsvBox.getHue();
                S = hsvBox.getSaturation();
                V = hsvBox.getValue();
                ShapeElement _previewerElement = new ShapeElement();
                _previewerElement.setShape(ShapeElement.OVAL);
                _previewerElement.setRgbColor(rgbColor);
                ColorPreviewer.setBackground(_previewerElement);
                Rgb_Value.setText("#"+ColorManager.getColorHex(rgbColor));
                Rgb_R.setText(CodeText);
            }
            catch (Exception e){}
        });

        Rgb_G.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                String CodeText = "";
                char[] texts = Rgb_G.getText().toCharArray();
                for(int o=0;o<texts.length;o++)
                {
                    if(TextManager.isNumCharPro(texts[o]))
                        CodeText += texts[o];
                }
                if(CodeText.length()>3)
                {
                    CodeText = CodeText.substring(0,3);
                }
                int val = Integer.valueOf(CodeText);
                if(val>255) CodeText = "255";
                G=val;
                slider_G.setProgressValue(G);
                RgbColor rgbColor = new RgbColor(R,G,B);
                colorValue = rgbColor.asArgbInt();
                ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(colorValue);
                H = hsvBox.getHue();
                S = hsvBox.getSaturation();
                V = hsvBox.getValue();
                ShapeElement _previewerElement = new ShapeElement();
                _previewerElement.setShape(ShapeElement.OVAL);
                _previewerElement.setRgbColor(rgbColor);
                ColorPreviewer.setBackground(_previewerElement);
                Rgb_Value.setText("#"+ColorManager.getColorHex(rgbColor));
                Rgb_G.setText(CodeText);
            }
            catch (Exception e){}
        });

        Rgb_B.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                String CodeText = "";
                char[] texts = Rgb_B.getText().toCharArray();
                for(int o=0;o<texts.length;o++)
                {
                    if(TextManager.isNumCharPro(texts[o]))
                        CodeText += texts[o];
                }
                if(CodeText.length()>3)
                {
                    CodeText = CodeText.substring(0,3);
                }
                int val = Integer.valueOf(CodeText);
                if(val>255) CodeText = "255";
                B=val;
                slider_B.setProgressValue(B);
                RgbColor rgbColor = new RgbColor(R,G,B);
                colorValue = rgbColor.asArgbInt();
                ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(colorValue);
                H = hsvBox.getHue();
                S = hsvBox.getSaturation();
                V = hsvBox.getValue();
                ShapeElement _previewerElement = new ShapeElement();
                _previewerElement.setShape(ShapeElement.OVAL);
                _previewerElement.setRgbColor(rgbColor);
                ColorPreviewer.setBackground(_previewerElement);
                Rgb_Value.setText("#"+ColorManager.getColorHex(rgbColor));
                Rgb_B.setText(CodeText);
            }
            catch (Exception e){}
        });

        slider_R.setMinValue(0);
        slider_R.setMaxValue(255);
        slider_R.setProgressValue(255);
        slider_R.setStep(1);

        slider_G.setMinValue(0);
        slider_G.setMaxValue(255);
        slider_G.setProgressValue(255);
        slider_G.setStep(1);

        slider_B.setMinValue(0);
        slider_B.setMaxValue(255);
        slider_B.setProgressValue(255);
        slider_B.setStep(1);

        if(DefaultColor!=-1)
        {
            colorValue = DefaultColor;
            ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(colorValue);
            H = hsvBox.getHue();
            S = hsvBox.getSaturation();
            V = hsvBox.getValue();

            RgbColor rgbColor = RgbColor.fromArgbInt(colorValue);
            R = rgbColor.getRed();
            G = rgbColor.getGreen();
            B = rgbColor.getBlue();

            ShapeElement _previewerElement = new ShapeElement();
            _previewerElement.setShape(ShapeElement.OVAL);
            _previewerElement.setRgbColor(rgbColor);
            ColorPreviewer.setBackground(_previewerElement);

            Rgb_Value.setText("#"+ColorManager.getColorHex(rgbColor));
            slider_R.setProgressValue(R);
            slider_G.setProgressValue(G);
            slider_B.setProgressValue(B);
            Rgb_R.setText(String.valueOf(R));
            Rgb_G.setText(String.valueOf(G));
            Rgb_B.setText(String.valueOf(B));
        }

        slider_R.setValueChangedListener(new Slider.ValueChangedListener()
        {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b)
            {
                R=i;
                Rgb_R.setText(String.valueOf(i));
                RgbColor rgbColor = new RgbColor(R,G,B);
                colorValue = rgbColor.asArgbInt();
                ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(colorValue);
                H = hsvBox.getHue();
                S = hsvBox.getSaturation();
                V = hsvBox.getValue();
                ShapeElement previewerElement = new ShapeElement();
                previewerElement.setShape(ShapeElement.OVAL);
                previewerElement.setRgbColor(rgbColor);
                ColorPreviewer.setBackground(previewerElement);
                Rgb_Value.setText("#"+ColorManager.getColorHex(rgbColor));
            }
            @Override
            public void onTouchStart(Slider slider) {}
            @Override
            public void onTouchEnd(Slider slider) {}
        });

        slider_G.setValueChangedListener(new Slider.ValueChangedListener()
        {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b)
            {
                G=i;
                Rgb_G.setText(String.valueOf(i));
                RgbColor rgbColor = new RgbColor(R,G,B);
                colorValue = rgbColor.asArgbInt();
                ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(colorValue);
                H = hsvBox.getHue();
                S = hsvBox.getSaturation();
                V = hsvBox.getValue();
                ShapeElement previewerElement = new ShapeElement();
                previewerElement.setShape(ShapeElement.OVAL);
                previewerElement.setRgbColor(rgbColor);
                ColorPreviewer.setBackground(previewerElement);
                Rgb_Value.setText("#"+ColorManager.getColorHex(rgbColor));
            }
            @Override
            public void onTouchStart(Slider slider) {}
            @Override
            public void onTouchEnd(Slider slider) {}
        });

        slider_B.setValueChangedListener(new Slider.ValueChangedListener()
        {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b)
            {
                B=i;
                Rgb_B.setText(String.valueOf(i));
                RgbColor rgbColor = new RgbColor(R,G,B);
                colorValue = rgbColor.asArgbInt();
                ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(colorValue);
                H = hsvBox.getHue();
                S = hsvBox.getSaturation();
                V = hsvBox.getValue();
                ShapeElement previewerElement = new ShapeElement();
                previewerElement.setShape(ShapeElement.OVAL);
                previewerElement.setRgbColor(rgbColor);
                ColorPreviewer.setBackground(previewerElement);
                Rgb_Value.setText("#"+ColorManager.getColorHex(rgbColor));
            }
            @Override
            public void onTouchStart(Slider slider) {}
            @Override
            public void onTouchEnd(Slider slider) {}
        });

        Component switchMode = dialogLayout.findComponentById(ResourceTable.Id_palette);
        switchMode.setClickedListener(c->
        {
            DatabaseManager.Init(mContext);
            DatabaseManager.setInt("ColorDialog_RgbMode",0);
            switchShow(initDialog());
        });
        Button button = (Button) dialogLayout.findComponentById(ResourceTable.Id_CloseButton);
        button.setBackground(new GeneralButtonElement(mContext,GeneralButtonElement.TYPE_Empty_Button));
        button.setTextColor(new Color(ResourceTool.getColor(mContext, ResourceTable.Color_dawnlighti_button_accent, -417762)));
        button.setText(mClose);
        button.setClickedListener(component -> {DatabaseManager.Init(mContext); DatabaseManager.setInt("ColorDialog_RgbMode",0); if (sDialog != null) {sDialog.destroy(); isDestroyed = true; System.gc();} });

        return dialogLayout;
    }

    public void saveTempColorValue()
    {
        DatabaseManager.Init(mContext);
        colorValue = HsvColor.toColor(255,H,S,V);
        DatabaseManager.setInt("ColorDialog_TempColorValue",colorValue);
    }

    public int getColorValue()
    {
        colorValue = HsvColor.toColor(255,H,S,V);
        return colorValue;
    }

    public ColorManager.HsvBox getHsvBox()
    {
        return new ColorManager.HsvBox(H,S,V);
    }

    public boolean isShowing()
    {
        return sDialog.isShowing();
    }

    public void destory()
    {
        sDialog.destroy();
        isDestroyed = true;
    }
}